package com.example.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

@Aspect
@Component
public class MethodCountAspect {

    private Map<String, AtomicInteger> methodMap = new ConcurrentHashMap<>();

    @Around("@annotation(com.example.annotation.MethodCount)")
    public Object count(ProceedingJoinPoint pjp) throws Throwable {
        Method method = ((MethodSignature)pjp.getSignature()).getMethod();
        String methodName = method.getName();
        try {
            return pjp.proceed();
        } catch (Throwable e) {
            throw e;
        }finally {
            AtomicInteger counter = methodMap.computeIfAbsent(methodName, k -> new AtomicInteger(0));
            counter.incrementAndGet();
        }
    }


    public int getMethodCount(String method){
        AtomicInteger atomicInteger = methodMap.get(method);
        return (atomicInteger!=null)? atomicInteger.get():0;
    }

}
